﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Utility;

namespace TimeTracker.XmlProvider
{
    public class XSessionElement : ISession
    {
        public XElement BaseElement
        {
            get;
            private set;
        }
        
        public XSessionElement(XElement other)
        {
            this.BaseElement = other;
        }

        public XSessionElement()
        {
            this.BaseElement = new XElement("session");
        }

        IProject ISession.Project
        {
            get {
                XElement element = this.BaseElement.Parent.Parent;

                if (element.Name == "project")
                {
                    return new XProjectElement(element);
                }

                return null;
            }
        }

        DateTime ISession.StartTime
        {
            get
            {
                return Convert.ToDateTime(this.BaseElement.Attribute("startTime").Value);
            }
            set
            {
                this.BaseElement.SetAttributeValue("startTime", value);
            }
        }

        DateTime? ISession.EndTime
        {
            get
            {
                return this.BaseElement.Attribute("stopTime") != null ? this.BaseElement.Attribute("stopTime").Value.ToNullable<DateTime>() : null;
            }
            set
            {
                this.BaseElement.SetAttributeValue("stopTime", value);
            }
        }

        bool ISession.Archived
        {
            get
            {
                return this.BaseElement.Element("archived") != null ? Convert.ToBoolean(this.BaseElement.Element("archived").Value) : false;
            }
            set
            {
                this.BaseElement.SetElementValue("archived", value);
                this.BaseElement.SetAttributeValue("archived", value);
            }
        }

        IEnumerable<INote> ISession.Notes
        {
            get {
                if (this.BaseElement.Element("notes") != null)
                {
                    return this.BaseElement.Element("notes").Elements("note").Select(r => new XNoteElement(r));
                }

                return new INote[] { };
            }
        }
    }
}
